import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:go_router/go_router.dart';
import 'package:multi_dropdown/multiselect_dropdown.dart';
import 'package:vdrag_saas/Utils.dart';
import 'package:vdrag_saas/api.dart';
import 'package:vdrag_saas/bus.dart';
import 'package:vdrag_saas/config.dart';
import 'package:vdrag_saas/list/pages/app_bar/app_bar_box.dart';
import 'package:vdrag_saas/list/pages/app_bar/search_widget.dart';
import 'package:vdrag_saas/list/pages/home/components/dropdown_options.dart';
import 'package:vdrag_saas/list/pages/home/footer_bar.dart';
import 'package:vdrag_saas/list/pages/home/product_type.dart';
import 'package:vdrag_saas/model/item_model.dart';
import 'package:vdrag_saas/list/pages/home/components/item_tile.dart';

class HomeTab extends StatefulWidget {
  const HomeTab({super.key});

  @override
  State<HomeTab> createState() => _HomeTabState();
}

class _HomeTabState extends State<HomeTab> {
  late ScrollController _scrollController = ScrollController();
  late Future<List<ItemModel>> productList;
  List<ItemModel> initList = [];
  List<String> filters = [];
  TextEditingController keywordsController = TextEditingController();
  bool appBarExpand = true;
  List<ValueItem> optionListSort = const [
    ValueItem(label: '默认排序', value: 1),
    ValueItem(label: '浏览数量', value: 2),
    ValueItem(label: '点赞数量', value: 3),
  ];
  String hintSort = "浏览数量";
  String hintType = "全部";

  /// 更新数据
  Future<List<ItemModel>> requestProductData([List<String>? filters_]) async {
    List<ItemModel> productList = await Api.listProduct(
      keywordsController.text,
      Global.type,
      filters_ ?? filters,
    );
    return productList;
  }

  void onBack() {
    onUpdate(filters);
  }

  // 点击标签后更新数据
  Future<List<String>> onUpdate(List<String> filters_) async {
    Future<List<ItemModel>> productList_ = requestProductData(filters_);
    setState(() {
      filters = filters_;
      productList = productList_;
    });
    List<ItemModel> productList_1 = await productList_;
    Set<String> tagSet = <String>{};

    for (var product in productList_1) {
      List<String> tags = product.labelArr;
      tagSet.addAll(tags);
    }
    return Future(() => tagSet.toList());
  }

  // 搜索后更新数据
  void onSearch(String val) async {
    Future<List<ItemModel>> productList_ = requestProductData();
    setState(() {
      // filters = filters_;
      productList = productList_;
    });
  }

  void onClear() {}

  @override
  void initState() {
    Global.fromHome = true;
    List<String> filters = [];
    onUpdate(filters);
    _scrollController = ScrollController()
      ..addListener(() {
        if (_scrollController.offset > 150) {
          setState(() {
            appBarExpand = false;
          });
        } else {
          setState(() {
            appBarExpand = true;
          });
        }
      });
    super.initState();
  }

  Widget buildAppContent() {
    return Flexible(
      child: Container(
        color: const Color(0xfff1f1f1),
        constraints: const BoxConstraints(maxWidth: 1300),
        padding: const EdgeInsetsDirectional.only(
            start: 12, end: 12, top: 0, bottom: 30),
        child: FutureBuilder(
            future: productList,
            initialData: initList,
            builder: (BuildContext context, AsyncSnapshot snapshot) {
              List<ItemModel> appData = [];
              if (snapshot.connectionState == ConnectionState.done) {
                if (!snapshot.hasError) {
                  appData = snapshot.data;
                }
              }
              return ListView.separated(
                  itemBuilder: (_, index) {
                    return ItemTile(
                      item: appData[index],
                      onBack: onBack,
                    );
                  },
                  separatorBuilder: (BuildContext context, index) {
                    return const SizedBox(
                      height: 20,
                    );
                  },
                  itemCount: appData.length);
            }),
      ),
    );
  }

  Widget buildPcContent() {
    return Expanded(
      child: SingleChildScrollView(
        child: Column(children: [
          Container(
            height: 640,
            color: const Color(0xfff1f1f1),
            constraints: const BoxConstraints(maxWidth: 1300),
            padding: const EdgeInsetsDirectional.only(
                start: 16, end: 16, top: 0, bottom: 30),
            child: FutureBuilder(
                future: productList,
                initialData: initList,
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  List<ItemModel> appData = [];
                  if (snapshot.connectionState == ConnectionState.done) {
                    if (!snapshot.hasError) {
                      appData = snapshot.data;
                    }
                  }
                  return GridView.builder(
                    shrinkWrap: true,
                    padding: EdgeInsets.zero,
                    physics: const BouncingScrollPhysics(),
                    gridDelegate:
                        const SliverGridDelegateWithMaxCrossAxisExtent(
                            maxCrossAxisExtent: 294,
                            mainAxisExtent: 294,
                            childAspectRatio: 294 / 256,
                            crossAxisSpacing: 40,
                            mainAxisSpacing: 0),
                    itemCount: appData.length,
                    itemBuilder: (_, index) {
                      return ItemTile(
                        item: appData[index],
                        onBack: onBack,
                      );
                    },
                  );
                }),
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  height: 268,
                  padding:
                      const EdgeInsetsDirectional.only(top: 30, bottom: 15),
                  color: const Color(0xff222222),
                  constraints: const BoxConstraints(minWidth: 1300),
                  child: Center(
                    child: FooterBar(),
                  ),
                ),
              )
            ],
          )
        ]),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    bool isMobile = Utils.isMobile(context);
    double appBarHeight = isMobile ? 108 : 150;
    double appExpandedBarHeight = isMobile ? 246 : 310;
    double screenWidth = MediaQuery.of(context).size.width;
    double innerWidth = screenWidth;
    Decoration? decoration;
    if (!isMobile && !appBarExpand) {
      decoration = const BoxDecoration(
          image: DecorationImage(
        image: AssetImage('assets/images/app-bar-bg-small.png'),
        fit: BoxFit.cover,
      ));
    }
    if (isMobile) {
      decoration = const BoxDecoration(color: Color(0xfff1f1f1));
    }
    return Scaffold(
      appBar: AppBar(
        toolbarHeight: isMobile ? 20 : 0,
        backgroundColor: const Color(0xfff1f1f1),
      ),
      body: Column(
        children: [
          Visibility(
            visible: !isMobile,
            child: Container(
              // decoration: const BoxDecoration(
              //   boxShadow: [
              //     // 设置单个阴影
              //     BoxShadow(
              //       color: Colors.amber, // 阴影颜色
              //       blurRadius: 4.0, // 模糊半径
              //       spreadRadius: 1.0, // 扩展半径（正值会使阴影扩大，负值会使阴影收缩）
              //       offset: Offset(0.0, 4.0), // 阴影相对于 `Container` 的偏移量
              //     ),
              //   ],
              // ),
              color: Colors.white,
              width: screenWidth,
              height: 45,
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Image.asset('assets/images/logo.png', width: 125, height: 45),
                ],
              ),
            ),
          ),
          Expanded(
            child: NestedScrollView(
              controller: _scrollController,
              headerSliverBuilder:
                  (BuildContext context, bool innerBoxIsScrolled) {
                // 创建一个始终浮动在顶部的SliverAppBar
                return [
                  SliverAppBar(
                    stretch: false,
                    backgroundColor: const Color(0xfff1f1f1),
                    toolbarHeight: appBarHeight,
                    pinned: true, // 设置为true，使其始终保持在顶部
                    expandedHeight: appExpandedBarHeight, // 搜索栏展开时的高度
                    scrolledUnderElevation: 0.0,
                    flexibleSpace: FlexibleSpaceBar(
                        expandedTitleScale: 1,
                        background: const AppBarBox(),
                        titlePadding: EdgeInsetsDirectional.zero,
                        collapseMode: CollapseMode.pin,
                        title: Column(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [
                              // Image.asset('assets/images/logo.png', width: 125, height: 45),
                              Container(
                                height: isMobile ? null : 150,
                                decoration: decoration,
                                constraints: BoxConstraints(
                                    maxWidth: innerWidth, minWidth: innerWidth),
                                padding: const EdgeInsetsDirectional.only(
                                    start: 12, end: 12, top: 14, bottom: 14),
                                child: SearchWidget(
                                  onUpdate,
                                  onSearch,
                                  keywordsController: keywordsController,
                                  onClear: onClear,
                                ),
                              ),
                            ])),
                  ),
                ];
              },
              body: Center(
                child: Container(
                  color: const Color(0xfff1f1f1),
                  child: Column(
                    children: [
                      Container(
                        constraints: const BoxConstraints(maxWidth: 1300),
                        color: const Color(0xfff1f1f1),
                        padding: const EdgeInsetsDirectional.only(
                            start: 12, end: 12, top: 0, bottom: 0),
                        child: Column(
                          children: [
                            Visibility(
                              visible: !isMobile,
                              child: const SizedBox(
                                height: 27,
                              ),
                            ),
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                isMobile? DropdownOptions(
                                  initList: [],
                                  url: '${HttpConfig.baseUrl}/api/types?sort=order',
                                  hint: hintType,
                                  onSort: () => onUpdate([]),
                                ): const Expanded(child: ProductType()),
                                DropdownOptions(
                                  initList: optionListSort,
                                  hint: hintSort,
                                  onSort: () => onUpdate([]),
                                ),
                              ],
                            ),
                            const SizedBox(
                              height: 10,
                            ),
                            Visibility(
                              visible: !isMobile,
                              child: const SizedBox(
                                height: 32,
                                child: Divider(),
                              ),
                            ),
                          ],
                        ),
                      ),
                      // buildAppContent()
                      isMobile ? buildAppContent() : buildPcContent()
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
